package com.kyub.spring.gears.web.upload;

import org.apache.commons.fileupload.ProgressListener;

import java.text.NumberFormat;

/**
 * Listener for upload progess
 */
public class FileUploadProgressListener implements ProgressListener {


    private long bytesTransferred = 0;

    private long fileSize = -100;

    private long tenKBRead = -1;

    public FileUploadProgressListener() {
    }


    public String getFileUploadStatus() {
        // per looks like 0% - 100%, remove % before submission
        String per = NumberFormat.getPercentInstance().format(
                (double) bytesTransferred / (double) fileSize);
        System.out.println(per + "** -> " + bytesTransferred);
        String perStr = per.substring(0, per.length() - 1);
        if (Integer.parseInt(perStr) >= 98)
            perStr = "100";
        return perStr;
    }

    public void update(long bytesRead, long contentLength, int items) {
        // update bytesTransferred and fileSize (if required) every 10 KB is
        // read
        long tenKB = bytesRead / 10240;
        if (tenKBRead == tenKB)
            return;
        tenKBRead = tenKB;

        bytesTransferred = bytesRead;

        //System.out.println("## ->" + bytesTransferred);

        if (fileSize != contentLength)
            fileSize = contentLength;
    }


}
